<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class MSharesBase extends MModel {
    
    public static function initSharesBase($path,$root) {
                                $shares_base = new MSharesBase();
        $user   = MUserManager::getInstance()->getCurrentUser();
        $shares_base->path    = MUtils::convertStandardPath($path);
        $shares_base->root    = $root;
                $shares_base->type    = "normal";
        $shares_base->user_id = $user->user_id;
        return $shares_base;
    }
    
    private function _getBaseUrl(){
    	$scriptName = $_SERVER["SCRIPT_NAME"];
    	return "http://".$_SERVER["HTTP_HOST"].rtrim(dirname($scriptName),'\\/');
    }
    
    public function create() {
                                $this->file_path = "/" . $this->user_id . $this->path;
        $query_db_file = MFiles::queryFilesByPath($this->file_path);
        if ($query_db_file === false || empty($query_db_file))
        {
            throw new MException(
                        FXP::t('No file was not found at the specified path.'),
                                MConst::HTTP_CODE_404);
        }
        $file_id = $query_db_file[0]["id"];
                                if ($this->type === "media") {
            if ($query_db_file[0]["file_type"] != MConst::OBJECT_TYPE_FILE) {
                throw new MException(
                        FXP::t('No file was not found at the specified path.'),
                                MConst::HTTP_CODE_404);
            }
        }
        
                                $this->expires = time() + (3 * 24 * 60 * 60);
                                $key = sha1($this->user_id.$file_id);
        $this->url = $this->_getBaseUrl()."/data.php/".MUrlManager::getAPIVersion()."/down_shares/".$key;
                                $ret_value = MShareFiles::queryShareByFileId($file_id);
        if ($ret_value)
        {
            $ret = MShareFiles::updateShareExpiresById($ret_value[0]["id"], $this->expires);
        }
        else
        {
            $ret = MShareFiles::CreateShareFile($key, $file_id, $this->expires);
        }
        if ($ret === false)
        {
            throw new MFileopsException(
                                        FXP::t('Internal Server Error'),
                                        MConst::HTTP_CODE_500);
        }
    }
    
    public function buildResult() {
        $response = array();
        $response["url"]        = $this->url;
        $response["expires"]    = MUtils::formatIntTime($this->expires);
        echo json_encode($response);
    }
}
?>